package com.store.framework.gui.view;

import java.awt.FlowLayout;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.store.framework.gui.model.CalculatorModel;

public class CalculatorView  extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8084941729481968185L;
	private static final String INITIAL_VALUE = "0";
	private JTextArea m_userInputTf = new JTextArea(5,30);
	private JTextField m_totalTf = new JTextField(20);
	private JButton m_lengthBtn = new JButton("length");
	private JButton m_clearBtn = new JButton("Clear");
	private CalculatorModel m_model;
	
	CalculatorView(CalculatorModel model){
		
		
			JScrollPane scroll = new JScrollPane(m_userInputTf); 
			//把定义的JTextArea放到JScrollPane里面去 

			//分别设置水平和垂直滚动条自动出现 
			scroll.setHorizontalScrollBarPolicy( 
			JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
			scroll.setVerticalScrollBarPolicy( 
			JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 

//			//分别设置水平和垂直滚动条总是出现 
//			scroll.setHorizontalScrollBarPolicy( 
//			JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
//			scroll.setVerticalScrollBarPolicy( 
//			JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
//
//			//分别设置水平和垂直滚动条总是隐藏
//			scroll.setHorizontalScrollBarPolicy( 
//			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
//			scroll.setVerticalScrollBarPolicy( 
//			JScrollPane.VERTICAL_SCROLLBAR_NEVER); 
			
		this.m_model = model;
		m_model.setValue(this.getUserInput().length()+"");

		JPanel content = new JPanel();
		content.setLayout(new FlowLayout());
		content.add(new JLabel("Input"));
		content.add(scroll);
		content.add(this.m_lengthBtn);
		content.add(new JLabel("TotalLength"));
		content.add(this.m_totalTf);
		content.add(this.m_clearBtn);
		this.setContentPane(content);
		this.pack();
		this.setTitle("Simple Calculator");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setAlwaysOnTop(true);
		reset();
	}

	public void reset(){
		this.m_totalTf.setText(INITIAL_VALUE);
		this.m_userInputTf.setText("");
	}
	public String getUserInput(){
		m_model.setValue(""+this.m_userInputTf.getText().length());
		return this.m_userInputTf.getText();
	}
	public void setTotal(String newTotal){
		this.m_totalTf.setText(newTotal);
	}
	public void showError(String errMessage){
		JOptionPane.showMessageDialog(this, errMessage);
	}
	public void addShowLengthListener(ActionListener mal){
		this.m_lengthBtn.addActionListener(mal);
	}
	public void addClearListener(ActionListener cal){
		this.m_clearBtn.addActionListener(cal);
	}
}
